<?php
require_once 'DbConnector.class.php';
/*TODO
 * Rajouter dans la table isadmin en boolean * 
 * */
class User
{
	/**
	*	Passwords are md5 summed, we'll suppose there's a SSL/TLS connection between the user and the server
	 */
	private $email;
	private $password;
	
	public function __construct($useremail, $password = null)
	{
		$this->email = $useremail;
	}
	
	// Authentication
	public static function auth($useremail, $password)
	{
		$authQuery = 'SELECT email, password FROM users WHERE email = \''.$useremail."' AND password ='".md5($password)."'";
		$stmt = DbConnector::get()->prepare($authQuery);
		$stmt->execute();
		if($stmt->rowcount() == 0)
			return null;
		else return new User($useremail);
	}
	public static function isadmin($email){
		$query="select isadmin from users where email ='".$email."'";
		$stmt=DbConnector::get()->prepare($query);
		$stmt->execute();
		$result=$stmt->fetchAll(PDO::FETCH_ASSOC);
		return $result[0]['isadmin'];
	}
	// 
	public static function register($user_email, $user_password)
	{
		// Check that the user's email is 'valid'
		$email_regex = "\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b";
		//if(preg_match("/$email_regex/", $user_email)) 	// Doesn't work
		if(true)											// Always works
		{
			$insQuery = "INSERT INTO users(email, password) VALUES ('".$user_email."', '".md5($user_password)."');";
			$stmt = DbConnector::get()->prepare($insQuery);
			if(!$stmt->execute())
				throw new Exception('User registration failed. Most likely already registered.');
		}
		else
			throw new Exception('User registration failed : not an email adress.');
		
		return new User($user_email, md5($user_password));
	}
	
	public function getEmail()
	{
		return $this->email;
	}
}